import React, { useState, useEffect, useRef } from 'react'
import { Space, Modal, message } from 'antd';
import { ProFormDateRangePicker, ProTable } from '@ant-design/pro-components';
import TheButton from "@/components/TheButton/index.jsx";
import { apiGetTimedTaskPage, apiGetCouponTimerCenterDel } from "@/api/couponManagement/timeTask.jsx";
import moment from 'moment';
import { useNavigate } from "react-router-dom";
import {useWindowSize} from "@/utils/useWindowSize.js";

const { confirm } = Modal
export default () => {
  const {width, height} = useWindowSize();
  const [tbScrollH, setTbScrollH] = useState('40vh');
  const navigate = useNavigate();
  const actionRef = useRef();
  const [loadings, setLoadings] = useState([]);
  const columns = [
    {
      title: "任务id",
      dataIndex: "couponTimerCenterId",
      key: "couponTimerCenterId",
    },
    {
      title: "发送时间",
      dataIndex: "pushDateTime",
      key: "pushDateTime",
      hideInSearch: true
    },
    {
      title: "任务时间",
      dataIndex: "taskTime",
      key: "taskTime",
      hideInTable: true,
      renderFormItem: () => {
        return <ProFormDateRangePicker
          formItemProps={{
            className: 'form-rangePicker-w',
          }}
        />
      },
      search: {
        transform: (value) => {
          return {
            start: value ? moment(value[0]).format('YYYY-MM-DD') + ' 00:00:00' : undefined,
            stop: value ? moment(value[1]).format('YYYY-MM-DD') + ' 23:59:59' : undefined,
          };
        }
      }
    },
    {
      title: "状态",
      dataIndex: "timerStatus",
      key: "timerStatus",
      valueEnum: {
        0: { text: '未开始', status: 'Default' },
        1: { text: '进行中', status: 'Processing' },
        2: { text: '已完成', status: 'Success' },
      },
    },
    {
      title: "结果",
      dataIndex: "timerResult",
      key: "timerResult",
      valueEnum: {
        0: { text: '未执行', status: 'Default' },
        1: { text: '成功', status: 'Success' },
        2: { text: '部分成功', status: 'Processing' },
        3: { text: '失败', status: 'Error' },
      },
      hideInSearch: true
    },
    {
      title: "最近修改时间",
      dataIndex: "updateTimeString",
      key: "updateTimeString",
      hideInSearch: true,
      valueType: 'dateTime',
      width: 250
    },
    {
      title: "操作",
      valueType: 'option',
      fixed: "right",
      render: (text, record, index) => {
        return (
          <Space>
            {record.timerStatus === 0 && <TheButton haspermi={['couponManagement:timedTask:edit']} type={'link'} onClick={() => onEdit(record)}>修改</TheButton>}
            <TheButton haspermi={['couponManagement:timedTask:view']} type={'link'} onClick={() => onView(record)}>查看</TheButton>
            {record.timerStatus === 0 && <TheButton haspermi={['couponManagement:timedTask:del']} type={'link'} onClick={() => onDel(record.couponTimerCenterId, index)} loading={loadings[index]}>删除</TheButton>}
            {record.timerStatus !== 0 && <TheButton haspermi={['couponManagement:timedTask:result']} type={'link'} onClick={() => onResult(record)}>发送结果</TheButton>}
          </Space>
        );
      },
    },
  ]
  const onAdd = () => {
    navigate('/couponManagement/timedTask/task', {
      state: {
        mode: "add"
      }
    })
  }
  const onEdit = (record) => {
    navigate('/couponManagement/timedTask/task', {
      state: {
        mode: "edit",
        id: record.couponTimerCenterId,
        time: record.pushDateTime
      }
    })
  }
  const onView = (record) => {
    navigate('/couponManagement/timedTask/task', {
      state: {
        mode: "view",
        id: record.couponTimerCenterId,
        time: record.pushDateTime
      }
    })
  }

  const onDel = (couponTimerCenterId, RowIndex) => {
    setLoadings((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      newLoadings[RowIndex] = true;
      return newLoadings;
    });
    confirm({
      title: "提示",
      type: 'warning',
      content: "确定是否删除？",
      onOk: async () => {
        let res = await apiGetCouponTimerCenterDel({ couponTimerCenterId })
        if (res.code === 0) {
          message.success('删除成功')
          actionRef.current.reloadAndRest();
        }
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      },
      onCancel: () => {
        setLoadings((prevLoadings) => {
          const newLoadings = [...prevLoadings];
          newLoadings[RowIndex] = false;
          return newLoadings;
        });
      }
    })
  }

  const onResult = (record) => {
    navigate('/couponManagement/timedTask/result', {
      state: {
        mode: "result",
        id: record.couponTimerCenterId,
      }
    })
  }

  useEffect(() => {
    if (height >= 1080){
      setTbScrollH('58vh')
    }else if(height < 1080 && height >= 960){
      setTbScrollH('45vh')
    }
  }, [])
  return <div>
    <ProTable
      actionRef={actionRef}
      scroll={{ x: "max-content", y: tbScrollH }}
      rowKey={(record) => record.memberId}
      bordered={true}
      options={false}
      columns={columns}
      headerTitle={
        <TheButton haspermi={['couponManagement:timedTask:add']} key="add" onClick={() => onAdd()}>新建</TheButton>
      }
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      request={async (params, sort, filter) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        if (params.timerStatus) {
          params.status = params.timerStatus
          delete params.timerStatus
        }

        const res = await apiGetTimedTaskPage({
          pageNo: params.current,
          pageSize: params.pageSize,
          ...params
        });

        return {
          data: res.rows,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: res.code === 0,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: res.totalCount,
        };
      }}
      search={{
        optionRender: (searchConfig, formProps, dom) => {
          return dom.reverse()
        },
        collapsed: false,
        collapseRender: false
      }}
    />
  </div>
}
